package com.hanbang.chu_xing_gao_zhao.view_find_standard;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hanbang.chu_xing_gao_zhao.adapter.BannerAdAdapter;
import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseDataActivity;
import com.hanbang.chu_xing_gao_zhao.entity.BannerAdData;
import com.hanbang.chu_xing_gao_zhao.entity.CommentData;
import com.hanbang.chu_xing_gao_zhao.entity.FindStadardDetailsData;
import com.hanbang.chu_xing_gao_zhao.myview.NumberSelectView;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.StringUtils_2;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.chu_xing_gao_zhao.view_public.DynamicCommentActivity;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

/**
 * 餐饮标准化——分类
 *
 * @author yang
 */
public class FindStandardDetailsActivity extends BaseDataActivity implements OnClickListener {
    /**
     * 图片轮播adapter
     */
    private BannerAdAdapter bannerAdAdapter;

    /**
     * 图片轮播集合
     */
    private ArrayList<BannerAdData> imageList;

    /**
     * 请求参数
     */
    private RequestParams params;
    /**
     * 评论列表
     */
    private ListView standardList;
    /**
     * 适配器
     */
    private ListViewAdapter adapter;
    /**
     * listView 头部
     */
    private View headerView;
    /**
     * 列表的数据
     */
    private ArrayList<CommentData> listData = new ArrayList<>();
    /**
     * 收藏
     */
    private CheckBox collect;

    private String userTlephone;
    private String userPassword;

    /**
     * 接口访问类型
     * 1是：得到当前的产品数据
     * 2是：加载评论
     * 3是：发表评论
     * 4是：判断是否收藏
     * 5是：收藏
     * 6是：取消收藏
     * 7是：分享
     */
    private int type = 1;

    /**
     * 访问类型
     */
    private int visitType = 3;
    private int pageSize = 10;
    private int pageIndex = 1;
    /**
     * 产品 id
     */
    private int id;
    private String title;
    private SwipeRefreshLayout swipeRefreshLayout;
    /**
     * 当前产品对象
     */
    private FindStadardDetailsData data;
    /**
     * 控制接口调用
     */
    int call = 0;

    /**
     * 数量选择
     */
    private NumberSelectView numberSelectView;
    /**
     * 数量计数
     */
    private int count = 1;

    /**
     * 显示价格
     */
    private TextView showSumPrice;
    /**
     * 产品名称
     */
    private TextView name;

    private WebView content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_standard_details_activity);
        initView();
        setOnClickListener();
        initImageCycleVeiw();
    }


    /**
     * 初始化view
     * pageSize：分页大小，可为空
     * pageIndex：当前页码，为空默认1
     * category_id：类别，如果获取全部的话，为0
     * sort_id：排序方式，0综合 ，销量1,评价2，价格高3，价格低4，免费5
     */
    private void initView() {
        userTlephone = MySharedPreferences.getSharedPreferencesKeyAndValue(FindStandardDetailsActivity.this, MySharedPreferences.USER_DATA, "tlephone");
        userPassword = MySharedPreferences.getSharedPreferencesKeyAndValue(FindStandardDetailsActivity.this, MySharedPreferences.USER_DATA, "password");
        headerView = getLayoutInflater().inflate(R.layout.find_standard_details_top_title, standardList, false);

        Intent intent = getIntent();
        id = intent.getIntExtra("id", 1);
        title = intent.getStringExtra("title");
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl_find_standard_activity_swipe);
        data = new FindStadardDetailsData();
        collect = (CheckBox) headerView.findViewById(R.id.cb_find_stadard_details_collect);
        numberSelectView = (NumberSelectView) headerView.findViewById(R.id.nsv_find_stadard_details_top_title_numSelect);
        showSumPrice = (TextView) findViewById(R.id.tv_find_standard_activity_price);
        content = (WebView) headerView.findViewById(R.id.wv_find_standard_details_top_title_webVie);
        name = (TextView) headerView.findViewById(R.id.tv_find_standard_details_top_title_name);

        //标题设置
        setTitleMore(View.VISIBLE, View.VISIBLE, title, null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));

        //控件初始化
        standardList = (ListView) findViewById(R.id.lv_find_standard_activity_list);


        // 列表添加适配器
        adapter = new ListViewAdapter(listData);
        standardList.addHeaderView(headerView);
        standardList.setAdapter(adapter);

        //获取餐饮标准化的详情
        type = 1;
        params = new RequestParams();
        params.addBodyParameter("telphone", userTlephone);
        params.addBodyParameter("password", userPassword);
        params.addBodyParameter("id", id + "");
        getHttpList(HttpInterfaces.GetGoodsDetails, params, 1);


        //调评论接口
        type = 2;
        RequestParams paramsB = new RequestParams();
        paramsB.addBodyParameter("telphone", userTlephone);
        paramsB.addBodyParameter("password", userPassword);
        paramsB.addBodyParameter("id", id + "");
        paramsB.addBodyParameter("type", visitType + "");
        paramsB.addBodyParameter("pageIndex", pageIndex + "");
        paramsB.addBodyParameter("pageSize", pageSize + "");
        getHttpList(HttpInterfaces.Comment_List, paramsB, type);

        //判断是否收藏
        type = 4;
        RequestParams paramsC = new RequestParams();
        paramsC.addBodyParameter("telphone", userTlephone);
        paramsC.addBodyParameter("password", userPassword);
        paramsC.addBodyParameter("id", id + "");
        paramsC.addBodyParameter("type", visitType + "");
        getHttpList(HttpInterfaces.IfFavorite, paramsC, type);


    }


    /**
     * 图片轮播的数据加载与调用
     */
    private void initImageCycleVeiw() {

        imageList = new ArrayList<BannerAdData>();

        // 初始化广告条 数据完成的时候要调用start
        bannerAdAdapter = new BannerAdAdapter(this,
                (RelativeLayout) headerView.findViewById(R.id.find_standard_details_top_title_cycle), imageList);
        bannerAdAdapter.setWidthAndHeight(16, 9);// 设置图片比例

        imageList.add(new BannerAdData(1, "http://img3.imgtn.bdimg.com/it/u=1887120881,51903778&fm=21&gp=0.jpg"));
        imageList.add(new BannerAdData(1, "http://img0.imgtn.bdimg.com/it/u=3045733783,3374698011&fm=21&gp=0.jpg"));
        imageList.add(new BannerAdData(1, "http://img4.imgtn.bdimg.com/it/u=12375103,1146398241&fm=21&gp=0.jpg"));
        imageList.add(new BannerAdData(1, "http://img5.imgtn.bdimg.com/it/u=2296455973,41150422&fm=21&gp=0.jpg"));

        bannerAdAdapter.notifyDataSetChanged();
        bannerAdAdapter.start();// 启动轮播

    }


    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        //评论添加 监听
        ((TextView) findViewById(R.id.tv_find_stadard_details_comment)).setOnClickListener(this);
        ((ImageView) findViewById(R.id.iv_find_standard_details_share)).setOnClickListener(this);
        ((LinearLayout) findViewById(R.id.ll_find_standard_details_top_title_service)).setOnClickListener(this);
        collect.setOnClickListener(this);

        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                listData.clear();
                pageIndex = 1;
                type = 2;
                params = new RequestParams();

                params.addBodyParameter("telphone", userTlephone);
                params.addBodyParameter("password", userPassword);
                params.addBodyParameter("id", id + "");
                params.addBodyParameter("type", visitType + "");
                params.addBodyParameter("pageSize", pageSize + "");
                params.addBodyParameter("pageIndex", pageIndex + "");

                getHttpList(HttpInterfaces.Comment_List, params, type);


                swipeRefreshLayout.setRefreshing(false);
            }
        });


        /**
         * 分享的回调
         */
        oks.setCallback(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                type = 7;
                RequestParams params = new RequestParams();
                params.addBodyParameter("telphone", userTlephone);
                params.addBodyParameter("password", userPassword);
                params.addBodyParameter("feed_id", userData.getId() + "");
                params.addBodyParameter("id", id + "");
                getHttpList(HttpInterfaces.Feed_Share, params, type);

            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });


        numberSelectView.setOnItemClickListener(new NumberSelectView.OnItemClickListener() {


            @Override
            public void onAddClick(int num, NumberSelectView view) {
                view.setNumber(++count);
                showSumPrice.setText(count * data.getPrice() + "");

            }

            @Override
            public void onSubClick(int num, NumberSelectView view) {
                view.setNumber(--count);
                showSumPrice.setText(count * data.getPrice() + "");
            }
        });


    }

    /**
     * 处理监听
     */


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            //判断图片或视频的点击
            case R.id.tv_find_stadard_details_comment:
                intent = new Intent(FindStandardDetailsActivity.this, DynamicCommentActivity.class);
                startActivityForResult(intent, 1213);
                break;

            //收藏
            case R.id.cb_find_stadard_details_collect:
                if (!collect.isSelected()) {
                    type = 5;
                    RequestParams params = new RequestParams();
                    params.addBodyParameter("telphone", userTlephone);
                    params.addBodyParameter("password", userPassword);
                    params.addBodyParameter("id", id + "");
                    params.addBodyParameter("type", visitType + "");
                    getHttpList(HttpInterfaces.Favorite_Add, params, type);
                } else {
                    type = 6;
                    RequestParams params = new RequestParams();
                    params.addBodyParameter("telphone", userTlephone);
                    params.addBodyParameter("password", userPassword);
                    params.addBodyParameter("id", id + "");
                    params.addBodyParameter("type", visitType + "");
                    getHttpList(HttpInterfaces.Favorite_Cancel, params, type);
                }

                break;
            //分享
            case R.id.iv_find_standard_details_share:
                showShare(getApplicationContext());
                break;
            //客服
            case R.id.ll_find_standard_details_top_title_service:
                intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "10086"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //得到编辑结果，发表评论
        if (requestCode == 1213 && resultCode == RESULT_OK) {
            type = 3;
            RequestParams params = new RequestParams();
            params = new RequestParams();
            params.addBodyParameter("telphone", userTlephone);
            params.addBodyParameter("password", userPassword);
            params.addBodyParameter("id", id + "");
            params.addBodyParameter("type", visitType + "");
            params.addBodyParameter("text", data.getStringExtra("commentText"));
            getHttpList(HttpInterfaces.Comment_Add, params, type);

//            MyLog.e("text", "0000*****" + data.getStringExtra("commentText"));

        }

    }

    /**
     * adapter 设置
     *
     * @author Administrator
     */
    class ListViewAdapter extends BaseAdapter {

        public ArrayList<CommentData> list = new ArrayList<CommentData>();

        public ListViewAdapter(ArrayList<CommentData> listData) {
            this.list = listData;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public CommentData getItem(int position) {

            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder viewHolder;
            if (convertView == null) {// 是空加载tiem
                convertView = getLayoutInflater().inflate(R.layout.item_find_classroom_details, null);
                UiUtils.applyFont(convertView);

                viewHolder = new ViewHolder();
                // 子控件初始化
                viewHolder.portraitId = (ImageView) convertView.findViewById(R.id.iv_tiem_find_classroom_details_portrait);
                viewHolder.name = (TextView) convertView.findViewById(R.id.tv_tiem_find_classroom_details_name);
                viewHolder.comment = (TextView) convertView.findViewById(R.id.tv_tiem_find_classroom_details_comment);
                viewHolder.time = (TextView) convertView.findViewById(R.id.tv_tiem_find_classroom_details_time);


                convertView.setTag(viewHolder);// 把现有有item对象存起来
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            final CommentData data = getItem(position);

            bitmapUtils.display(viewHolder.portraitId, SystemTools.getHttpFileUrl(data.getAvatar()));

            viewHolder.name.setText(data.getUser_name());
            viewHolder.comment.setText(data.getText());
            viewHolder.time.setText("评论时间:" + StringUtils_2.getTime(data.getAdd_time()));

//            MyLog.e("text", "position*****" + position+"***listData.size()***"+listData.size());

            //自动加载
            if (position == listData.size() - 1) {

                if (call < 0) {
                    return convertView;
                }
                ++pageIndex;
                type = 2;
                RequestParams paramsB = new RequestParams();
                paramsB.addBodyParameter("telphone", userTlephone);
                paramsB.addBodyParameter("password", userPassword);
                paramsB.addBodyParameter("id", id + "");
                paramsB.addBodyParameter("type", visitType + "");
                paramsB.addBodyParameter("pageIndex", pageIndex + "");
                paramsB.addBodyParameter("pageSize", pageSize + "");
                getHttpList(HttpInterfaces.Comment_List, paramsB, type);


            }


            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            // 子控件主要是里面的数据
            private ImageView portraitId;
            private TextView name;
            private TextView comment;
            private TextView time;

        }

    }

    /**
     * 获取网格数据
     */
    private void getHttpList(String url, RequestParams params, final int type) {
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new MyRequestCallBack<String>(this, "加载中...") {


            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);


                    /**
                     * 产品内容
                     */
                    if (type == 1) {
                        boolean result = json.getBoolean("Result");
                        if (result) {
                            //1.先解析成一个object类型
                            JSONObject dataObject = json.getJSONObject("model");
                            //2.转换成具体对象
                            data = JsonHelper.parseObject(dataObject, FindStadardDetailsData.class);
                            ((TextView) findViewById(R.id.tv_find_stadard_details_price)).setText(String.valueOf(data.getPrice()));
                            ((TextView) findViewById(R.id.tv_find_stadard_details_sale)).setText(String.valueOf(data.getBuycount()));
                            ((TextView) findViewById(R.id.tv_find_stadard_details_grade)).setText(String.valueOf(data.getPinfen()));
                            name.setText(data.getRemark());
                            // 设置内容， webView 加载Strig 类型Html
//                            content.loadData(data.getText(), "text/html", "UTF-8");


                            configWebview();
                            upDateUI();


                        }
                        return;
                    }

                    //得到评论
                    if (type == 2) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            JSONArray jsonArray = json.getJSONArray("list");
                            //如果是空则停止接口的自动调用
                            if (jsonArray.length() == 0) {
                                call = -1;
                                MyToast.show(FindStandardDetailsActivity.this, "没有更多内容", 1);
                                return;
                            }
                            call = 0;
                            listData.addAll(JsonHelper.parseCollection(jsonArray, ArrayList.class, CommentData.class));
                            showSumPrice.setText(count * data.getPrice() + "");
                            adapter.notifyDataSetChanged();
                        }
                    }

                    //发表评论
                    if (type == 3) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            MyToast.show(FindStandardDetailsActivity.this, "评论成功", 1);
                        }
                    }


                    //判断是否收藏
                    if (type == 4) {
                        boolean result = json.getBoolean("Result");
                        if (result) {
                            boolean IfFavorite = json.getBoolean("IfFavorite");
                            if (IfFavorite) {
                                collect.setSelected(true);
                                ((TextView) findViewById(R.id.tv_find_stadard_details_collect)).setText("已收藏");
                            } else {
                                collect.setSelected(false);
                                ((TextView) findViewById(R.id.tv_find_stadard_details_collect)).setText("收藏");
                            }

                        }
                    }


                    //收藏
                    if (type == 5) {
                        int result = json.getInt("Result");
                        if (result == 0) {

                            collect.setSelected(true);
                            ((TextView) findViewById(R.id.tv_find_stadard_details_collect)).setText("已收藏");

                        }
                    }

                    //取消收藏
                    if (type == 6) {
                        int result = json.getInt("Result");
                        if (result == 0) {

                            collect.setSelected(false);
                            ((TextView) findViewById(R.id.tv_find_classroom_details_collect)).setText("收藏");

                        }
                    }


                    //分享
                    if (type == 7) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            MyToast.show(FindStandardDetailsActivity.this, "分享成功", 1);
                        }
                    }


                } catch (Exception e) {
                    MyToast.show(FindStandardDetailsActivity.this, "网编异常请稍后再试", 1);
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 重新设置webview 属性
     */

    @SuppressWarnings("unused")
    private void configWebview() {
        // 设置文本编码
        content.getSettings().setDefaultTextEncodingName("utf-8");
        // 可以缩放
        content.getSettings().setSupportZoom(true);
        content.getSettings().setJavaScriptEnabled(true);
        content.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        content.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 开启 Application Caches 功能
        content.getSettings().setAppCacheEnabled(false);
        content.getSettings().setLoadWithOverviewMode(true);
        // webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);// 默认缩放模式
        content.getSettings().setUseWideViewPort(false);
    }

    /**
     * 获取到服务器数据后开始跟新UI
     */
    private void upDateUI() {

        // 配置webview数据源
        data.setText("<style type=\"text/css\">*{ line-height:30px;}*{ font-size:15px;}img{WIDTH:100% !important;HEIGHT:auto !important;}"
                + getFont()
                + "</style><base href=\""
                + HttpInterfaces.ORG
                + "\"/>"
                + "<body class=\"Likun\" style=\"padding-left:2%;padding-right:2%;\">" + data.getText() + "</body>");


        // 设置webview 加载数据
        content.loadDataWithBaseURL(null, data.getText(), "text/html", "utf-8", null);
        MyLog.e("loadDataWithBaseURL", data.getText());
    }

    /**
     * 更新字体
     *
     * @return
     */
    private String getFont() {
        StringBuilder builder = new StringBuilder();
        // <body class="MsoNormal"> </body>
        builder.append(".Likun { font-family: fzlt;}");
        builder.append("@font-face {font-family:fzlt;");
        builder.append("src:url(file:///android_asset/fzlt.ttf);}");
        return builder.toString();
    }
}


